using System;
using System.Collections.Generic;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// 交易时机评分系统 - 基于多维度指标的综合评分体系
    /// 整合波动率水平、趋势强度和市场流动性三个核心维度，
    /// 为不同波动环境提供科学的交易策略建议
    /// </summary>
    public class TradingTimingScorer
    {
        #region 常量定义

        // 评分权重设置
        public const double VOLATILITY_WEIGHT = 0.4;         // 波动率水平权重40%
        public const double TREND_STRENGTH_WEIGHT = 0.3;     // 趋势强度权重30%
        public const double MARKET_LIQUIDITY_WEIGHT = 0.3;   // 市场流动性权重30%

        // 波动率环境分级阈值
        public const double LOW_VOLATILITY_THRESHOLD = 0.01;       // 低波动阈值1%
        public const double MEDIUM_VOLATILITY_THRESHOLD = 0.025;   // 中等波动阈值2.5%
        public const double HIGH_VOLATILITY_THRESHOLD = 0.05;      // 高波动阈值5%

        // 趋势强度分级阈值
        public const double WEAK_TREND_THRESHOLD = 0.3;      // 弱趋势阈值
        public const double MODERATE_TREND_THRESHOLD = 0.6;  // 中等趋势阈值
        public const double STRONG_TREND_THRESHOLD = 0.8;    // 强趋势阈值

        // 流动性分级阈值
        public const double LOW_LIQUIDITY_THRESHOLD = 50;     // 低流动性阈值（交易笔数）
        public const double MEDIUM_LIQUIDITY_THRESHOLD = 200; // 中等流动性阈值
        public const double HIGH_LIQUIDITY_THRESHOLD = 500;   // 高流动性阈值

        // 评分等级阈值
        public const double EXCELLENT_SCORE_THRESHOLD = 80;   // 优秀评分阈值
        public const double GOOD_SCORE_THRESHOLD = 65;        // 良好评分阈值
        public const double AVERAGE_SCORE_THRESHOLD = 50;     // 平均评分阈值
        public const double POOR_SCORE_THRESHOLD = 35;        // 较差评分阈值

        // 动态阈值调整参数
        public const double ADAPTATION_FACTOR = 0.1;          // 适应性调整因子
        public const int HISTORICAL_PERIOD = 20;              // 历史数据周期

        #endregion

        #region 私有字段

        // 历史数据存储
        private readonly List<double> _historicalVolatilities;
        private readonly List<double> _historicalTrendStrengths;
        private readonly List<double> _historicalLiquidities;
        private readonly List<TradingTimingScoreDetail> _historicalScores;

        // 动态阈值
        private double _dynamicVolatilityThreshold;
        private double _dynamicTrendThreshold;
        private double _dynamicLiquidityThreshold;

        // 性能统计
        private readonly Dictionary<VolatilityEnvironmentLevel, EnvironmentPerformance> _performanceStats;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化交易时机评分系统
        /// </summary>
        public TradingTimingScorer()
        {
            _historicalVolatilities = new List<double>();
            _historicalTrendStrengths = new List<double>();
            _historicalLiquidities = new List<double>();
            _historicalScores = new List<TradingTimingScoreDetail>();

            // 初始化动态阈值
            _dynamicVolatilityThreshold = MEDIUM_VOLATILITY_THRESHOLD;
            _dynamicTrendThreshold = MODERATE_TREND_THRESHOLD;
            _dynamicLiquidityThreshold = MEDIUM_LIQUIDITY_THRESHOLD;

            // 初始化性能统计
            _performanceStats = new Dictionary<VolatilityEnvironmentLevel, EnvironmentPerformance>
            {
                { VolatilityEnvironmentLevel.Low, new EnvironmentPerformance() },
                { VolatilityEnvironmentLevel.Medium, new EnvironmentPerformance() },
                { VolatilityEnvironmentLevel.High, new EnvironmentPerformance() },
                { VolatilityEnvironmentLevel.Extreme, new EnvironmentPerformance() }
            };
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 计算综合交易时机评分
        /// </summary>
        /// <param name="currentVolatility">当前波动率</param>
        /// <param name="trendStrength">趋势强度</param>
        /// <param name="marketLiquidity">市场流动性</param>
        /// <param name="currentPrice">当前价格</param>
        /// <param name="historicalPrices">历史价格数据</param>
        /// <returns>交易时机评分结果</returns>
        public TradingTimingScoreDetail CalculateTimingScore(
            double currentVolatility,
            double trendStrength,
            double marketLiquidity,
            double currentPrice,
            List<double> historicalPrices = null)
        {
            // 更新历史数据
            UpdateHistoricalData(currentVolatility, trendStrength, marketLiquidity);

            // 计算各维度评分
            double volatilityScore = CalculateVolatilityScore(currentVolatility);
            double trendScore = CalculateTrendScore(trendStrength);
            double liquidityScore = CalculateLiquidityScore(marketLiquidity);

            // 计算综合评分
            double overallScore = (volatilityScore * VOLATILITY_WEIGHT) +
                                 (trendScore * TREND_STRENGTH_WEIGHT) +
                                 (liquidityScore * MARKET_LIQUIDITY_WEIGHT);

            // 分类波动率环境
            var volatilityEnvironment = ClassifyVolatilityEnvironment(currentVolatility);

            // 生成交易策略建议
            var strategy = GenerateTradingStrategy(volatilityEnvironment, overallScore, trendStrength);

            // 创建评分结果
            var timingScore = new TradingTimingScoreDetail
            {
                OverallScore = Math.Round(overallScore, 2),
                VolatilityScore = Math.Round(volatilityScore, 2),
                TrendScore = Math.Round(trendScore, 2),
                LiquidityScore = Math.Round(liquidityScore, 2),
                VolatilityEnvironment = volatilityEnvironment,
                TradingAdvice = GetTradingAdvice(overallScore),
                Strategy = strategy,
                Timestamp = DateTime.Now
            };

            // 记录评分历史
            _historicalScores.Add(timingScore);
            if (_historicalScores.Count > HISTORICAL_PERIOD)
            {
                _historicalScores.RemoveAt(0);
            }

            return timingScore;
        }

        /// <summary>
        /// 更新环境性能统计
        /// </summary>
        /// <param name="environment">波动率环境</param>
        /// <param name="tradingSuccess">交易成功</param>
        /// <param name="profitLoss">盈亏</param>
        public void UpdatePerformanceStats(VolatilityEnvironmentLevel environment, bool tradingSuccess, double profitLoss)
        {
            if (_performanceStats.ContainsKey(environment))
            {
                var stats = _performanceStats[environment];
                stats.TotalTrades++;
                stats.TotalProfitLoss += profitLoss;

                if (tradingSuccess)
                {
                    stats.SuccessfulTrades++;
                }

                stats.SuccessRate = (double)stats.SuccessfulTrades / stats.TotalTrades;
                stats.AverageProfitLoss = stats.TotalProfitLoss / stats.TotalTrades;
            }
        }

        /// <summary>
        /// 获取环境性能报告
        /// </summary>
        /// <returns>性能报告</returns>
        public Dictionary<VolatilityEnvironmentLevel, EnvironmentPerformance> GetPerformanceReport()
        {
            return new Dictionary<VolatilityEnvironmentLevel, EnvironmentPerformance>(_performanceStats);
        }

        /// <summary>
        /// 动态调整评分阈值
        /// </summary>
        public void AdjustDynamicThresholds()
        {
            if (_historicalVolatilities.Count >= HISTORICAL_PERIOD)
            {
                // 基于历史数据调整波动率阈值
                double avgVolatility = _historicalVolatilities.Average();
                _dynamicVolatilityThreshold = avgVolatility * (1 + ADAPTATION_FACTOR);

                // 基于历史数据调整趋势阈值
                double avgTrendStrength = _historicalTrendStrengths.Average();
                _dynamicTrendThreshold = avgTrendStrength * (1 + ADAPTATION_FACTOR);

                // 基于历史数据调整流动性阈值
                double avgLiquidity = _historicalLiquidities.Average();
                _dynamicLiquidityThreshold = avgLiquidity * (1 + ADAPTATION_FACTOR);
            }
        }

        /// <summary>
        /// 获取评分系统状态报告
        /// </summary>
        /// <returns>状态报告</returns>
        public string GetStatusReport()
        {
            var report = $"交易时机评分系统状态报告 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n";
            report += $"历史数据点数: {_historicalScores.Count}\n";
            report += $"动态波动率阈值: {_dynamicVolatilityThreshold:F4}\n";
            report += $"动态趋势阈值: {_dynamicTrendThreshold:F4}\n";
            report += $"动态流动性阈值: {_dynamicLiquidityThreshold:F0}\n\n";

            report += "各环境性能统计:\n";
            foreach (var kvp in _performanceStats)
            {
                var env = kvp.Key;
                var stats = kvp.Value;
                report += $"{env}环境: 交易{stats.TotalTrades}次, 成功率{stats.SuccessRate:P2}, 平均盈亏{stats.AverageProfitLoss:F2}\n";
            }

            return report;
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 更新历史数据
        /// </summary>
        private void UpdateHistoricalData(double volatility, double trendStrength, double liquidity)
        {
            _historicalVolatilities.Add(volatility);
            _historicalTrendStrengths.Add(trendStrength);
            _historicalLiquidities.Add(liquidity);

            // 保持历史数据大小
            if (_historicalVolatilities.Count > HISTORICAL_PERIOD)
            {
                _historicalVolatilities.RemoveAt(0);
            }
            if (_historicalTrendStrengths.Count > HISTORICAL_PERIOD)
            {
                _historicalTrendStrengths.RemoveAt(0);
            }
            if (_historicalLiquidities.Count > HISTORICAL_PERIOD)
            {
                _historicalLiquidities.RemoveAt(0);
            }
        }

        /// <summary>
        /// 计算波动率评分
        /// 基于市场条件动态计算交易时机评分
        /// </summary>
        private double CalculateVolatilityScore(double volatility)
        {
            // 基础分数基于波动率区间
            double baseScore = 50.0;
            
            if (volatility <= LOW_VOLATILITY_THRESHOLD)
            {
                // 低波动环境评分计算
                // 波动率因子（0-1）：波动率越低，评分越高
                double volatilityFactor = 1.0 - (volatility / LOW_VOLATILITY_THRESHOLD);
                
                // 趋势强度加成（0-20分）
                double trendBonus = GetCurrentTrendStrength() * 20.0;
                
                // 市场条件调整（-10到+10分）
                double marketAdjustment = GetMarketConditionAdjustment();
                
                // 计算最终分数
                baseScore = 60.0 + (volatilityFactor * 15.0) + trendBonus + marketAdjustment;
            }
            else if (volatility <= _dynamicVolatilityThreshold)
            {
                // 中等波动环境
                double normalizedVolatility = (volatility - LOW_VOLATILITY_THRESHOLD) / 
                                             (_dynamicVolatilityThreshold - LOW_VOLATILITY_THRESHOLD);
                baseScore = 75.0 - (normalizedVolatility * 5.0) + GetMarketConditionAdjustment();
            }
            else if (volatility <= HIGH_VOLATILITY_THRESHOLD)
            {
                // 高波动环境
                double normalizedVolatility = (volatility - _dynamicVolatilityThreshold) / 
                                             (HIGH_VOLATILITY_THRESHOLD - _dynamicVolatilityThreshold);
                baseScore = 60.0 - (normalizedVolatility * 10.0) + GetRiskAdjustment();
            }
            else
            {
                // 极端波动环境
                double extremeFactor = Math.Min(1.0, (volatility - HIGH_VOLATILITY_THRESHOLD) / HIGH_VOLATILITY_THRESHOLD);
                baseScore = 35.0 - (extremeFactor * 15.0);
            }
            
            // 确保分数在合理范围内
            return Math.Max(0.0, Math.Min(100.0, baseScore));
        }
        
        /// <summary>
        /// 获取当前趋势强度（归一化到 0-1）
        /// </summary>
        private double GetCurrentTrendStrength()
        {
            // 从历史趋势强度数据计算平均值
            if (_historicalTrendStrengths.Count > 0)
            {
                // 取最近5个数据点的平均值
                int count = Math.Min(5, _historicalTrendStrengths.Count);
                double sum = 0;
                for (int i = _historicalTrendStrengths.Count - count; i < _historicalTrendStrengths.Count; i++)
                {
                    sum += _historicalTrendStrengths[i];
                }
                return Math.Min(1.0, sum / count);
            }
            return 0.5; // 默认中等趋势
        }
        
        /// <summary>
        /// 获取市场条件调整值
        /// </summary>
        private double GetMarketConditionAdjustment()
        {
            // 基于历史评分统计的调整
            if (_historicalScores.Count > 0)
            {
                // 计算最近评分的成功率
                int recentCount = Math.Min(10, _historicalScores.Count);
                double avgScore = 0;
                for (int i = _historicalScores.Count - recentCount; i < _historicalScores.Count; i++)
                {
                    avgScore += _historicalScores[i].OverallScore;
                }
                avgScore /= recentCount;
                
                // 根据平均分数调整（如果历史表现好，给予正向调整）
                return (avgScore - 60.0) / 10.0; // -6 到 +4 的调整
            }
            return 0.0;
        }
        
        /// <summary>
        /// 获取风险调整值
        /// </summary>
        private double GetRiskAdjustment()
        {
            // 基于波动率历史数据的风险调整
            if (_historicalVolatilities.Count > 0)
            {
                // 计算最近波动率的标准差
                int count = Math.Min(10, _historicalVolatilities.Count);
                double sum = 0, sumSquared = 0;
                for (int i = _historicalVolatilities.Count - count; i < _historicalVolatilities.Count; i++)
                {
                    sum += _historicalVolatilities[i];
                    sumSquared += _historicalVolatilities[i] * _historicalVolatilities[i];
                }
                double mean = sum / count;
                double variance = (sumSquared / count) - (mean * mean);
                double stdDev = Math.Sqrt(variance);
                
                // 标准差越小，风险调整越积极
                return Math.Max(-5.0, Math.Min(3.0, (0.02 - stdDev) * 100));
            }
            return 0.0;
        }
        
        /// <summary>
        /// 计算最近失败率
        /// </summary>
        private double CalculateRecentFailureRate()
        {
            // 基于性能统计计算失败率
            if (_performanceStats.Count > 0)
            {
                double totalSuccess = 0;
                double totalTrades = 0;
                foreach (var stat in _performanceStats.Values)
                {
                    totalSuccess += stat.SuccessfulTrades;
                    totalTrades += stat.TotalTrades;
                }
                if (totalTrades > 0)
                {
                    return 1.0 - (totalSuccess / totalTrades);
                }
            }
            return 0.3; // 默认30%失败率
        }

        /// <summary>
        /// 计算趋势评分
        /// </summary>
        private double CalculateTrendScore(double trendStrength)
        {
            if (trendStrength >= STRONG_TREND_THRESHOLD)
            {
                // 强趋势 - 优秀交易机会
                return 90.0;
            }
            else if (trendStrength >= _dynamicTrendThreshold)
            {
                // 中等趋势 - 良好交易机会
                return 70.0;
            }
            else if (trendStrength >= WEAK_TREND_THRESHOLD)
            {
                // 弱趋势 - 一般交易机会
                return 50.0;
            }
            else
            {
                // 无明显趋势 - 较差交易机会
                return 30.0;
            }
        }

        /// <summary>
        /// 计算流动性评分
        /// </summary>
        private double CalculateLiquidityScore(double liquidity)
        {
            if (liquidity >= HIGH_LIQUIDITY_THRESHOLD)
            {
                // 高流动性 - 优秀执行条件
                return 90.0;
            }
            else if (liquidity >= _dynamicLiquidityThreshold)
            {
                // 中等流动性 - 良好执行条件
                return 70.0;
            }
            else if (liquidity >= LOW_LIQUIDITY_THRESHOLD)
            {
                // 低流动性 - 一般执行条件
                return 50.0;
            }
            else
            {
                // 极低流动性 - 较差执行条件
                return 25.0;
            }
        }

        /// <summary>
        /// 分类波动率环境
        /// </summary>
        private VolatilityEnvironmentLevel ClassifyVolatilityEnvironment(double volatility)
        {
            if (volatility <= LOW_VOLATILITY_THRESHOLD)
                return VolatilityEnvironmentLevel.Low;
            else if (volatility <= _dynamicVolatilityThreshold)
                return VolatilityEnvironmentLevel.Medium;
            else if (volatility <= HIGH_VOLATILITY_THRESHOLD)
                return VolatilityEnvironmentLevel.High;
            else
                return VolatilityEnvironmentLevel.Extreme;
        }

        /// <summary>
        /// 生成交易策略建议
        /// </summary>
        private TradingStrategy GenerateTradingStrategy(VolatilityEnvironmentLevel environment, double score, double trendStrength)
        {
            var strategy = new TradingStrategy();

            switch (environment)
            {
                case VolatilityEnvironmentLevel.Low:
                    // 低波动环境策略：提高频率，收紧止损
                    strategy.TradingFrequency = 1.5; // 增加50%频率
                    strategy.StopLossMultiplier = 0.8; // 收紧20%止损
                    strategy.PositionSizeMultiplier = 1.2; // 增加20%仓位
                    strategy.RecommendedAction = "积极交易 - 适合趋势跟踪";
                    break;

                case VolatilityEnvironmentLevel.Medium:
                    // 中等波动环境策略：标准交易参数
                    strategy.TradingFrequency = 1.0; // 标准频率
                    strategy.StopLossMultiplier = 1.0; // 标准止损
                    strategy.PositionSizeMultiplier = 1.0; // 标准仓位
                    strategy.RecommendedAction = "正常交易 - 使用标准策略";
                    break;

                case VolatilityEnvironmentLevel.High:
                    // 高波动环境策略：降低频率，增加止损
                    strategy.TradingFrequency = 0.7; // 减少30%频率
                    strategy.StopLossMultiplier = 1.3; // 放宽30%止损
                    strategy.PositionSizeMultiplier = 0.8; // 减少20%仓位
                    strategy.RecommendedAction = "谨慎交易 - 加强风险控制";
                    break;

                case VolatilityEnvironmentLevel.Extreme:
                    // 极端波动环境策略：暂停交易
                    strategy.TradingFrequency = 0.3; // 大幅减少频率
                    strategy.StopLossMultiplier = 1.5; // 大幅放宽止损
                    strategy.PositionSizeMultiplier = 0.5; // 大幅减少仓位
                    strategy.RecommendedAction = "避免交易 - 等待市场稳定";
                    break;
            }

            // 根据综合评分进一步调整
            if (score >= EXCELLENT_SCORE_THRESHOLD)
            {
                strategy.PositionSizeMultiplier *= 1.1; // 优秀评分增加10%仓位
            }
            else if (score <= POOR_SCORE_THRESHOLD)
            {
                strategy.PositionSizeMultiplier *= 0.8; // 较差评分减少20%仓位
            }

            return strategy;
        }

        /// <summary>
        /// 获取交易建议
        /// </summary>
        private string GetTradingAdvice(double overallScore)
        {
            if (overallScore >= EXCELLENT_SCORE_THRESHOLD)
                return "优秀 - 强烈推荐交易";
            else if (overallScore >= GOOD_SCORE_THRESHOLD)
                return "良好 - 推荐交易";
            else if (overallScore >= AVERAGE_SCORE_THRESHOLD)
                return "一般 - 可考虑交易";
            else if (overallScore >= POOR_SCORE_THRESHOLD)
                return "较差 - 谨慎考虑";
            else
                return "很差 - 不建议交易";
        }

        #endregion

        #region 辅助数据结构

        /// <summary>
        /// 波动率环境级别
        /// </summary>
        public enum VolatilityEnvironmentLevel
        {
            Low,        // 低波动环境
            Medium,     // 中等波动环境
            High,       // 高波动环境
            Extreme     // 极端波动环境
        }

        /// <summary>
        /// 交易时机评分详细结果
        /// </summary>
        public class TradingTimingScoreDetail
        {
            public double OverallScore { get; set; }                        // 综合评分
            public double VolatilityScore { get; set; }                     // 波动率评分
            public double TrendScore { get; set; }                          // 趋势评分
            public double LiquidityScore { get; set; }                      // 流动性评分
            public VolatilityEnvironmentLevel VolatilityEnvironment { get; set; } // 波动率环境
            public string TradingAdvice { get; set; }                       // 交易建议
            public TradingStrategy Strategy { get; set; }                   // 交易策略
            public DateTime Timestamp { get; set; }                         // 时间戳
        }

        /// <summary>
        /// 交易策略
        /// </summary>
        public class TradingStrategy
        {
            public double TradingFrequency { get; set; }          // 交易频率倍数
            public double StopLossMultiplier { get; set; }        // 止损倍数
            public double PositionSizeMultiplier { get; set; }    // 仓位倍数
            public string RecommendedAction { get; set; }         // 推荐操作
        }

        /// <summary>
        /// 环境性能统计
        /// </summary>
        public class EnvironmentPerformance
        {
            public int TotalTrades { get; set; } = 0;             // 总交易次数
            public int SuccessfulTrades { get; set; } = 0;        // 成功交易次数
            public double SuccessRate { get; set; } = 0.0;        // 成功率
            public double TotalProfitLoss { get; set; } = 0.0;    // 总盈亏
            public double AverageProfitLoss { get; set; } = 0.0;  // 平均盈亏
        }

        #endregion
    }
}
